package com.weme.common.base

import android.util.Log
import androidx.lifecycle.ViewModel
import com.google.protobuf.ByteString
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.osom.proto.message.CommonOuterClass
import com.osom.proto.message.NetworkOuterClass
import com.weme.chat.bean.CallMessage
import com.weme.common.BaseApplication
import com.weme.common.R
import com.weme.common.dialog.PermissingDialog
import com.weme.common.manager.SocketConnectManager.callVideoLiveData
import com.weme.common.manager.SocketManager
import com.weme.common.network.CallsPhone
import com.weme.common.network.NetWorkUrl
import com.weme.common.util.*
import dev.kratos.api.user_server.v1.GetAccountInfoRequest
import dev.kratos.api.user_server.v1.GetUserInfoRequest
import dev.kratos.api.user_server.v1.Users
import io.agora.chat.ChatClient
import io.agora.chat.ChatMessage
import io.agora.chat.CustomMessageBody
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel


open class BaseViewModel : ViewModel() {
    // 创建 ViewModel 时自动创建一个 CoroutineScope
    protected val viewModelScope = CoroutineScope(Dispatchers.Main)
    val APPID = 1000

    // 取消 ViewModel 时取消 CoroutineScope
    public override fun onCleared() {
        super.onCleared()

        viewModelScope.cancel()
    }

    fun sendNetworkRequest(req: ByteArray, netWorkUrl: NetWorkUrl) {
        val baseReq = CommonOuterClass.BaseRequest.newBuilder().setService("user_server.v1.User").setMethod(netWorkUrl.method).setAppid(APPID).setSesskey(UserMKHelper.decodeString(UserMKHelper.SESSION)).setLang(CommonUtils().getCurrentSystemLanguage()).setVerApp(DeviceUtils.getVersionName()).setTime(System.currentTimeMillis()).setUid(UserMKHelper.decodeLong(UserMKHelper.UID)).setParam(ByteString.copyFrom(req)).setDeviceid(DeviceId.getAndroidId().toString()).build()
        Log.e("socket", "sendNetworkRequest call -> 发送消息 " + "seq= " + netWorkUrl.seq + " method = ${netWorkUrl.method}")
        val commonData = ByteString.copyFrom(baseReq.toByteArray())


        try {
            SocketManager.send(commonData, NetworkOuterClass.NetworkCommand.CMD_GATEWAY_API_REQUEST.number, netWorkUrl.seq)
        } catch (e: Exception) {
            Log.e("socket", "error  seq= " + netWorkUrl.seq + " method = ${netWorkUrl.method}")
            LoadingDailog.dismiss() //log.error(e)
        }
    }

    fun sendCmsNetworkRequest(req: ByteArray, netWorkUrl: NetWorkUrl) {
        val baseReq = CommonOuterClass.BaseRequest.newBuilder().setService("cms_server.v1.Cms").setMethod(netWorkUrl.method).setAppid(APPID).setSesskey(UserMKHelper.decodeString(UserMKHelper.SESSION)).setLang(CommonUtils().getCurrentSystemLanguage()).setVerApp(DeviceUtils.getVersionName()).setTime(System.currentTimeMillis()).setUid(UserMKHelper.decodeLong(UserMKHelper.UID)).setParam(ByteString.copyFrom(req)).setDeviceid(DeviceId.getAndroidId().toString()).build()
        Log.e("socket", "sendCmsNetworkRequest call -> 发送消息 " + "seq= " + netWorkUrl.seq + " method = ${netWorkUrl.method}")
        val commonData = ByteString.copyFrom(baseReq.toByteArray())


        try {
            SocketManager.send(commonData, NetworkOuterClass.NetworkCommand.CMD_GATEWAY_API_REQUEST.number, netWorkUrl.seq)
        } catch (e: Exception) { //log.error(e)
        }
    }


    fun sendImNetworkRequest(req: ByteArray, netWorkUrl: NetWorkUrl) {
        val baseReq = CommonOuterClass.BaseRequest.newBuilder().setService("im_server.v1.Im").setMethod(netWorkUrl.method).setAppid(APPID).setSesskey(UserMKHelper.decodeString(UserMKHelper.SESSION)).setLang(CommonUtils().getCurrentSystemLanguage()).setVerApp(DeviceUtils.getVersionName()).setTime(System.currentTimeMillis()).setUid(UserMKHelper.decodeLong(UserMKHelper.UID)).setParam(ByteString.copyFrom(req)).setDeviceid(DeviceId.getAndroidId().toString()).build()
        Log.e("socket", "sendImNetworkRequest call -> 发送消息 " + "seq= " + netWorkUrl.seq + " method = ${netWorkUrl.method}")
        val commonData = ByteString.copyFrom(baseReq.toByteArray())


        try {
            SocketManager.send(commonData, NetworkOuterClass.NetworkCommand.CMD_GATEWAY_API_REQUEST.number, netWorkUrl.seq)
        } catch (e: Exception) {
            Log.e("socket", "error  seq= " + netWorkUrl.seq + " method = ${netWorkUrl.method}")
            LoadingDailog.dismiss() //log.error(e)
        }
    }


    fun sendAccountworkRequest(req: ByteArray, netWorkUrl: NetWorkUrl) {
        val baseReq = CommonOuterClass.BaseRequest.newBuilder().setService("account_server.v1.Account").setMethod(netWorkUrl.method).setAppid(APPID).setSesskey(UserMKHelper.decodeString(UserMKHelper.SESSION)).setLang(CommonUtils().getCurrentSystemLanguage()).setVerApp(DeviceUtils.getVersionName()).setTime(System.currentTimeMillis()).setUid(UserMKHelper.decodeLong(UserMKHelper.UID)).setParam(ByteString.copyFrom(req)).setDeviceid(DeviceId.getAndroidId().toString()).build()
        Log.e("socket", "sendAccountworkRequest  call -> 发送消息 " + "seq= " + netWorkUrl.seq + " method = ${netWorkUrl.method}")
        val commonData = ByteString.copyFrom(baseReq.toByteArray())


        try {
            SocketManager.send(commonData, NetworkOuterClass.NetworkCommand.CMD_GATEWAY_API_REQUEST.number, netWorkUrl.seq)
        } catch (e: Exception) {
            Log.e("socket", "error  seq= " + netWorkUrl.seq + " method = ${netWorkUrl.method}")
            LoadingDailog.dismiss() //log.error(e)
        }
    }


    fun getAccountInfo() {
        val reqByte = GetAccountInfoRequest.newBuilder().setUid(UserMKHelper.decodeLong(UserMKHelper.UID)).build().toByteArray()
        sendNetworkRequest(reqByte, NetWorkUrl.GetAccountInfo)
    }

    fun getUserInfo() {
        val reqByte = GetUserInfoRequest.newBuilder().build().toByteArray()
        sendNetworkRequest(reqByte, NetWorkUrl.MineGetUserInfo)
    }

    fun callsPhone(user: Users) {
//        if (user.isBlack) {
//            UtilsApp.getTopActivity().showToast(UtilsApp.getTopActivity().getString(com.example.resources.R.string.block_you))
//            return
//        }
        val isDenied = mutableListOf(Permission.RECORD_AUDIO, Permission.CAMERA, Permission.WRITE_EXTERNAL_STORAGE).all { XXPermissions.isGranted(BaseApplication.sInstance, it) }
        if (isDenied) {

            callPhoneInt(user)
        } else {
            val permissingDialog = PermissingDialog(UtilsApp.getTopActivity(), mutableListOf(Permission.RECORD_AUDIO, Permission.CAMERA, Permission.WRITE_EXTERNAL_STORAGE)) {
                callPhoneInt(user)
            }
            permissingDialog.show(UtilsApp.getTopActivity().supportFragmentManager, "")
        }

    }

    private fun callPhoneInt(user: Users) {
        callVideoLiveData.postValue(CallsPhone(user)) //im的逻辑  现在弃用
        //        val javaList = mutableListOf<String>()
        //        javaList.add(user.uid.toString())
        //        ChatClient.getInstance().presenceManager().fetchPresenceStatus(javaList, object : ValueCallBack<List<Presence?>> {//获取用户是否在线
        //            override fun onSuccess(presences: List<Presence?>?) {
        //                if(presences!!.isNotEmpty()){
        //                    callVideoLiveData.postValue(CallsPhone(user))
        //                }else{
        //                    sendImMsg(user.uid.toString())
        //                    MyApplication.sInstance.showToast("不在线")
        //                }
        //            }
        //
        //            override fun onProgress(progress: Int, status: String?) {
        //                super.onProgress(progress, status)
        //
        //            }
        //            override fun onError(errorCode: Int, errorMsg: String) {
        //
        //            }
        //        })
    }


}